<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/8/4 09:55
 */

namespace App\Project\Reserve\Statistics;

use App\Models\Reservation\Reservation;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Collection;

class Situation
{
    protected $time;

    protected $user;

    public function __construct(User $user, $time)
    {
        $this->user = $user;

        $this->time = $time;
    }

    public function get()
    {
        $collect = Reservation::select(['id', 'am', 'start', 'end'])
                              ->where([
                                      'time'      => $this->time,
                                      'doctor_id' => $this->user->id,
                                      'status'    => 2,
                                  ])->get();

        if (!$collect->count()) {
            return [];
        }

        $data = ['am' => 0, 'pm' => 0];

        $data['total'] = $collect->count();

        $collect->groupBy('am')->map(
            function (Collection $value, $key) use (&$data) {
                if ($key) {
                    $data['am'] = $value->count();
                } else {
                    $data['pm'] = $value->count();
                }
            }
        );

        $data['section'] = $collect->sortBy('start')->map(
            function ($section) {
                $time               = Carbon::parse($section->time)->startOfDay();
                $section['section'] = $time->hour($section->start)->format('H:i')
                    . '-'
                    . $time->hour($section->end)->format('H:i');

                return $section;
            })->groupBy('section')->map(function (Collection $item) {
                return $item->count();
            }
        )->all();

        return $data;
    }
}